package com.example.ymm.modules1.service.impl.hl.ex;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.ex.ExTeam;
import com.example.ymm.modules1.entity.hl.ex.ExTeamRule;
import com.example.ymm.modules1.entity.hl.ex.ExTeamUser;
import com.example.ymm.modules1.entity.my.user.DbUser;
import com.example.ymm.modules1.mapper.ex.ExTeamMapper;
import com.example.ymm.modules1.query.hl.ex.ExTeamQueryCriteria;
import com.example.ymm.modules1.query.hl.ex.ExTeamRuleQueryCriteria;
import com.example.ymm.modules1.query.hl.ex.ExTeamUserQueryCriteria;
import com.example.ymm.modules1.service.dto.heng.ex.ImportTeamDataDto;
import com.example.ymm.modules1.service.hl.ex.ExTeamRuleService;
import com.example.ymm.modules1.service.hl.ex.ExTeamService;
import com.example.ymm.modules1.service.hl.ex.ExTeamUserService;
import com.example.ymm.modules1.service.user.DbUserService;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
@DS("slave2")
public class ExTeamServiceImpl extends BaseServiceImpl<ExTeamMapper, ExTeam> implements ExTeamService {

    @Autowired
    DbUserService dbUserService;

    @Autowired
    ExTeamUserService exTeamUserService;
    @Autowired
    private ExTeamRuleService exTeamRuleService;

    @Override
    public TableList<ExTeam> list(ExTeamQueryCriteria criteria, YmPageDto pageDto) {
        IPage<ExTeam> page = new Page<ExTeam>(pageDto.getPage(),pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(ExTeam.class, criteria);
        predicate.orderByAsc("sort");
        baseMapper.selectPage(page, predicate);
        TableList<ExTeam> tableList=new TableList(page);
        return tableList;
    }

    public List<ExTeam> queryAll(ExTeamQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(ExTeam.class, criteria);
        predicate.orderByAsc("sort");
        List<ExTeam> result =baseMapper.selectList(predicate);
        return result;
    }

    @Override
    public void teamSave(ExTeam exTeam) {
        if(UtilValidate.isEmpty(exTeam.getName())){
            throw new YmException("参数异常!");
        }
        boolean isAdd = false;
        if (exTeam.getTeamId() == null) {
            isAdd = true;
        }
        saveOrUpdate(exTeam);
        if (!isAdd) {
            LambdaQueryWrapper<ExTeamUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ExTeamUser::getTeamId, exTeam.getTeamId());
            exTeamUserService.remove(queryWrapper);
        }
        List<ExTeamUser> items = exTeam.getItems();
        items.forEach(item -> {
            item.setTeamId(exTeam.getTeamId());
        });
        exTeamUserService.saveOrUpdateBatch(items);

    }

    @Override
    public ExTeam teamDetail(String teamId) {
        ExTeam team = getById(teamId);
        ExTeamUserQueryCriteria criteria=new ExTeamUserQueryCriteria();
        criteria.setTeamId(teamId);
        List<ExTeamUser> exTeamUsers = exTeamUserService.queryAll(criteria);
        team.setItems(exTeamUsers);

        ExTeamRuleQueryCriteria c1= new ExTeamRuleQueryCriteria();
        c1.setTeamId(teamId);
        List<ExTeamRule> exTeamRules = exTeamRuleService.queryAll(c1);
        team.setRules(exTeamRules);
        return team;
    }

    @Override
    public List<String> importTeam(ImportTeamDataDto dto) {
        List<String> msg = new ArrayList<String>();
        List<JSONObject> list = dto.getList();
        if(UtilValidate.isEmpty(list)){
            throw new YmException("数据不能为空!");
        }
        Map<String,String> map = new HashMap<String,String>();
        Map<String,List<DbUser>> map_user = new HashMap<String,List<DbUser>>();
        JSONObject one = list.get(0);
        List<ExTeam> teams=new ArrayList<>();
        one.keySet().forEach(key -> {
            String value = one.getString(key).trim();
            map.put(key,one.getString(key));
            ExTeamQueryCriteria c2 = new ExTeamQueryCriteria();
            c2.setName(value);
            List<ExTeam> teams1 = queryAll(c2);
            ExTeam exTeam = null;
            if(UtilValidate.isNotEmpty(teams1)){
                exTeam =teams1.get(0);
            }else{
                exTeam = new ExTeam();
            }
            exTeam.setName(value);
            Integer sort=Integer.parseInt(value.replaceAll("组",""));
            exTeam.setSort(sort);
            exTeam.setDeptName(key);
            teams.add(exTeam);
            map_user.put(key,new ArrayList<>());
        });
        list.remove(0);
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push("master");
        for(JSONObject obj : list){
            obj.keySet().forEach(key -> {
                String user_name = obj.getString(key).trim();
                if(UtilValidate.isNotEmpty(user_name)){
                    if(!user_name.contains("房地产")&&!user_name.contains("工业旅游")){
                        DbUser dbUser = dbUserService.findByUserName(user_name);
                        if(UtilValidate.isEmpty(dbUser)){
                            msg.add(user_name+"查找不到\n");
                        }
                        if(UtilValidate.isNotEmpty(dbUser)){
                            List<DbUser> arr = map_user.get(key);
                            arr.add(dbUser);
                            map_user.put(key,arr);
                        }
                    }else{
                        DbUser dbUser=new DbUser();
                        dbUser.setUserName(user_name);
                        dbUser.setUserId("场外人员:"+user_name);
                        List<DbUser> arr = map_user.get(key);
                        arr.add(dbUser);
                        map_user.put(key,arr);
                    }
                }
            });
        }
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push("slave2");
//        System.out.println(map_user);
        for(ExTeam team: teams){
            String deptName = team.getDeptName();
            saveOrUpdate(team);
            List<DbUser> dbUsers = map_user.get(deptName);
            List<ExTeamUser> exTeamUsers = new ArrayList<>();
            for(DbUser dbUser : dbUsers){
                ExTeamUser exTeamUser = exTeamUserService.findByUserName(dbUser.getUserName());
                if(UtilValidate.isEmpty(exTeamUser)){
                    exTeamUser = new ExTeamUser();
                    exTeamUser.setTeamId(team.getTeamId());
                    exTeamUser.setUserId(dbUser.getUserId());
                    exTeamUser.setUserName(dbUser.getUserName());
                }else{
                    exTeamUser.setTeamId(team.getTeamId());
                    exTeamUser.setTeamName(team.getDeptName());
                }
                exTeamUsers.add(exTeamUser);
            }
            exTeamUserService.saveOrUpdateBatch(exTeamUsers);

        }
        return msg;
    }


    @Override
    public ExTeam geyByName(String name) {
        ExTeamQueryCriteria criteria=new ExTeamQueryCriteria();
        criteria.setName(name);
        List<ExTeam> teams = queryAll(criteria);
        if(UtilValidate.isNotEmpty(teams)){
            return teams.get(0);
        }

        return null;
    }
}
